using System;
using System.Collections.Generic;
using System.Threading;
using WIT.DAQ.Core.Models;

namespace WIT.DAQ.Core.Helper;

/// <summary>
/// 超时帮助类
/// </summary>
internal class TimeoutHelper
{
	private ManualResetEvent mTimeoutObject;

	private bool mBoTimeout;

	/// <summary>
	/// 可能超时要异步执行的方法
	/// </summary>
	internal DoHandler Do;

	/// <summary>
	/// 构造函数
	/// </summary>
	internal TimeoutHelper()
	{
		mTimeoutObject = new ManualResetEvent(initialState: true);
	}

	/// <summary>
	/// 指定超时时间 异步执行某个方法
	/// </summary>
	/// <param name="millisecondsTimeout">超时时间(ms)</param>
	/// <param name="station">站点</param>
	/// <param name="task">任务</param>
	/// <param name="connectionPool">连接池</param>
	/// <param name="devices">设备列表</param>
	/// <param name="socketData">接收到的SocketServer数据</param>
	/// <param name="ignoreTrigger">是否忽略触发条件</param>
	/// <returns></returns>
	internal bool DoWithTimeout(int millisecondsTimeout, Station station, DAQTask task, List<Connection> connectionPool, List<Device> devices, byte[] socketData = null, bool ignoreTrigger = false)
	{
		if (Do == null)
		{
			return false;
		}
		mTimeoutObject.Reset();
		mBoTimeout = true;
		Do.BeginInvoke(station, task, connectionPool, devices, socketData, ignoreTrigger, DoAsyncCallBack, null);
		if (!mTimeoutObject.WaitOne(millisecondsTimeout, exitContext: false))
		{
			mBoTimeout = true;
		}
		return mBoTimeout;
	}

	/// <summary>
	///  异步委托 回调函数
	/// </summary>
	/// <param name="result"></param>
	private void DoAsyncCallBack(IAsyncResult result)
	{
		try
		{
			Do.EndInvoke(result);
			mBoTimeout = false;
		}
		catch (Exception ex)
		{
			Console.WriteLine(ex.Message);
			mBoTimeout = true;
		}
		finally
		{
			mTimeoutObject.Set();
		}
	}
}
